﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.Core.Repositories;
using System.Web;
using MvcEngine.Core.Account;
using MvcEngine.Core.Extensions;

namespace MvcEngine.Core.Helpers
{
    public class PermissionHelper : IPermissionHelper
    {
        private HttpContextBase context = null;

        public PermissionHelper(HttpContextBase context)
        {
            this.context = context;
        }

        public PermissionHelper()
            : this(new HttpContextWrapper(HttpContext.Current))
        {

        }

        public static IPermissionHelper Current
        {
            get { return IoC.Resolve<IPermissionHelper>(); }
        }


        public bool HasRights(User user, int pageContentId, string key)
        {
            IList<Role> userRoles = AccountManager.Current.GetRolesForUser(user);
            if (userRoles.Any(u => u.Name == Constants.Roles.Administrators))
                return true;

            IList<Permission> permissions = AccountManager.Current.GetPermissions();
            IList<ControlPermission> controlPermissions = AccountManager.Current.GetControlPermissions(pageContentId);

            var result = from p in permissions
                         join mp in controlPermissions on p.Id equals mp.PermissionId
                         join r in userRoles on mp.RoleId equals r.Id
                         where r.SiteId == SiteContext.Current.Site.Id && mp.PageContentId == pageContentId && p.Key == key
                         select p;

            return result.Any();
        }

        public bool HasRights(int pageContentId, string key)
        {
            return HasRights(UserContext.Current.User, pageContentId, key);
        }

        public bool HasRights(User user, Guid pageId, string key)
        {
            IList<Role> userRoles = AccountManager.Current.GetRolesForUser(user);
            if (userRoles.Any(u => u.Name == Constants.Roles.Administrators))
                return true;

            IList<Permission> permissions = AccountManager.Current.GetPermissions();
            IList<PagePermission> controlPermissions = AccountManager.Current.GetPagePermissions(pageId);

            var result = from p in permissions
                         join mp in controlPermissions on p.Id equals mp.PermissionId
                         join r in userRoles on mp.RoleId equals r.Id
                         where r.SiteId == SiteContext.Current.Site.Id && mp.PageId == pageId && p.Key == key
                         select p;

            return result.Any();
        }

        public bool HasRights(Guid pageId, string key)
        {
            return HasRights(UserContext.Current.User, pageId, key);
        }
    }
}
